package com.ibm.epss.android;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class PackageExpressActivity extends ActionBarActivity {

    private ListView inComingView;
    private SimpleAdapter myPackages;
    private ActivityProfile activityProfile = ActivityProfile.getInstance();
    private Button newOrderBtn;


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
        tabHost.setup();
        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("In Coming")
                .setContent(R.id.view1));
        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("New Order")
                .setContent(R.id.view2));
        inComingView = (ListView) findViewById(R.id.view1);

        buildMyPackages();
        inComingView.setAdapter(myPackages);

        setupMQTTClient();
        setupOrderTracking();

    }

    private void setupOrderTracking() {
       newOrderBtn=(Button) findViewById(R.id.btnSubmit);
       newOrderBtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               JSONObject order = new JSONObject();
               try {
                   order.put("from","SH");
                   order.put("to","BJ");
                   order.put("STATUS","new");
                   OrderTrackingRestClient.postJSONObject("http://nebular.cn.ibm.com:8080/pess/service/flow/new-order", "", "", order);
               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
       });
    }


    private void setupMQTTClient() {
        try {
            if (isWifiAvailable(this.getApplicationContext())) {
             /*
              *  init PropertiesEntity
              * */
                Log.i("PackageExpressActivity", "loadActitityProfile");
                activityProfile.loadActitityProfile((TelephonyManager) this
                        .getSystemService(Context.TELEPHONY_SERVICE));
            /*
             *  start mqtt client
             * */
                if (MQTTHelper.isConnected()) {
                    Log.i("PackageExpressActivity", activityProfile.getLog());
                }

                Log.d("MQTT", "conn request");
                int returnCode = MQTTHelper.Connect();
                if (returnCode == 0) {
                    Log.i("MQTT", "connected.");
                    startService(new Intent(this, MqttService.class));
                }

                /**
                 * subscribe topic
                 */

                if (MQTTHelper.Subscribe() == 0) {
                    Log.i("MQTT", "Topic subscribed!");
                } else {
                    Log.i("MQTT", "Subscribe failed! ");
                }
            }
        } catch (Exception e) {
            Log.e("MQTT", "Fail to setup MQTT Client.");
        }

    }

    public boolean isWifiAvailable(Context context) {
        boolean rc = false;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //cm.getActiveNetworkInfo().isConnectedOrConnecting();
        NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        rc = wifi.isConnected() || mobile.isConnected();
        return rc;
    }

    private HashMap<String, String> getPackageItem(final String name, final String location) {
        HashMap<String, String> pkg = new HashMap<String, String>();
        pkg.put("PackageName", name);
        pkg.put("PackageLoc", location);
        return pkg;
    }

    private void buildMyPackages() {
        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
        mylist.add(getPackageItem("Book <The Everything Store: Jeff Bezos and the Age of Amazon> ", "Xi Er Qi,Beijing"));
        mylist.add(getPackageItem("Laptop Apple Mac Pro", "Shang Di,Beijing"));
        myPackages = new SimpleAdapter(this, mylist,
                R.layout.package_items,
                new String[]{"PackageName", "PackageLoc"},
                new int[]{R.id.PackageName, R.id.PackageLoc});
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (MQTTHelper.isConnected()) {
            Log.i("PackageExpressActivity", "onResume mqtt connected");
        }
        activityProfile.setCtxActivity(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.action_msgs:
                Log.i("onOptionsItemSelected","action_msgs");
                openMsgs();
                return true;
            case R.id.action_refresh:
                refreshOrders();
                // for demo use
                closeOrder();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void closeOrder() {
        try {
            OrderTrackingRestClient.postJSONObject("http://nebular.cn.ibm.com:8080/pess/service/flow/close-order","","",new JSONObject());
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }


    private void refreshOrders() {

    }

    private void openMsgs() {
        //To change body of created methods use File | Settings | File Templates.
        Intent intent = new Intent();
        intent.setClass(this, PackageExpressNotificationActivity.class);
        Log.i("onOptionsItemSelected","startActivity PackageExpressNotificationActivity");
        startActivity(intent);
        this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_activity_actions, menu);
        return super.onCreateOptionsMenu(menu);
    }
}
